import {
  Image,
  StyleProp,
  Text,
  TouchableOpacity,
  View,
  ViewStyle,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import styles from "./RowButton.style";
import React, { ReactNode } from "react";
import { ImageResource } from "@/types/common";
import { useTheme } from "@/contexts/ThemeContext";

interface RowButtonProps {
  text: string | ImageResource;
  icon?: any;
  style?: StyleProp<ViewStyle>;
  tailText?: string;
  tailComponent?: ReactNode;
  onPress?: () => void;
  isLast?: boolean;
}

/**
 * 行按钮组件
 * @param text
 * @param icon
 * @param tailText
 * @param onPress
 * @param style
 * @param tailComponent 尾部组件，当该选项不为空时，onPress
 * @param isLast
 * @constructor
 */
export default function RowButton({
  text,
  icon,
  tailText,
  onPress,
  style,
  tailComponent,
  isLast = false,
}: RowButtonProps) {
  // 使用自定义主题
  const { colors } = useTheme();

  const renderLastComponent = () => {
    if (tailComponent) {
      return tailComponent;
    } else {
      if (tailText) {
        return (
          <Text
            numberOfLines={1}
            ellipsizeMode="tail"
            style={[styles.tailText, { color: colors.text.secondary }]}
          >
            {tailText}
          </Text>
        );
      } else {
        return (
          <Ionicons
            name="chevron-forward-outline"
            size={20}
            color={colors.text.secondary}
          />
        );
      }
    }
  };

  const renderIcon = () => {
    if (!icon) {
      return <></>;
    }
    if (typeof icon === "string") {
      return (
        <View style={styles.iconContainer}>
          {/*// @ts-ignore*/}
          <Ionicons name={icon} size={22} color={colors.primary} />
        </View>
      );
    } else {
      return <View style={styles.iconContainer}>{icon}</View>;
    }
  };

  const renderRowButton = () => {
    const content = (
      <View
        style={[styles.item, { backgroundColor: colors.background }, style]}
      >
        {renderIcon()}
        {typeof text === "string" ? (
          <Text
            numberOfLines={1}
            style={[styles.text, { color: colors.text.primary }]}
          >
            {text}
          </Text>
        ) : (
          <Image source={{ uri: text.src }} style={styles.image} />
        )}
        {renderLastComponent()}
      </View>
    );

    const divider = !isLast && (
      <View
        style={[
          styles.divider,
          {
            backgroundColor: colors.border.divider,
            marginLeft: icon ? 52 : 16,
          },
        ]}
      />
    );

    if (onPress) {
      return (
        <TouchableOpacity onPress={onPress} activeOpacity={0.7}>
          {content}
          {divider}
        </TouchableOpacity>
      );
    } else {
      return (
        <>
          {content}
          {divider}
        </>
      );
    }
  };

  return <>{renderRowButton()}</>;
}
